-- 避免队列中存在相同的字母
-- 添加关卡（1，教学关卡，2，其他模式）
function love.load()
  winWidth = 350
  winHeight = 350
  love.window.setMode(winWidth, winHeight) 

  alphabets = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  showSeconds = 3
  initWaitSeconds = 2
  waitSeconds = 0
  font = love.graphics.newFont("font.ttf",35)
  font2 = love.graphics.newFont("font.ttf",50)
  level = 0
  score = 0
  life = 10

  allSa = {}
  table.insert(allSa,sa)
end

function love.keypressed(key, scancode, isrepeat)
  if key == "escape" then
     love.event.quit()
  end
  for k,v in ipairs(allSa) do
    if string.upper(key) == v["text"] then
      table.remove(allSa,k)
      score = score + 1
      if #allSa == 0 then
        addNew()
      end
      if score % 10 == 0 then
        level = level + 1
        if showSeconds >= 1 then
          showSeconds = showSeconds -  0.1 * (level % 10)  
        end
        if initWaitSeconds >= 0.5 then
          initWaitSeconds = initWaitSeconds - 0.1 * (level % 10)  
        end
      end
    end
  end
end

function love.update(dt)
  if life <= 0 then
    return
  end
  for k,v in ipairs(allSa) do
    v["showSeconds"] = v["showSeconds"] - dt
    if v["showSeconds"] <= 0 then
      table.remove(allSa,k)
      life = life - 1
    end
  end
  waitSeconds = waitSeconds - dt
  if waitSeconds <= 0 then
    addNew()
  end
end

function love.draw()
  if life <= 0 then
    table.remove(allSa)
    love.graphics.print('GAME OVER',font2,50,130)
  end
  love.graphics.print("SCORE: "..score,20,20)
  love.graphics.print("LIFE: "..life,280,20)
  -- love.graphics.print("LEVEL: "..level,250,20)
  for k,v in ipairs(allSa) do
    drawKey(v["text"],v["x"],v["y"])
  end 
end

function addNew()
  local sa = {}
  local la = 1
  if level <= 5 then
    la = 11
  end
  local pos = love.math.random(la,#alphabets)
  sa["text"] = string.sub(alphabets,pos,pos)
  sa["showSeconds"] = showSeconds
  sa["x"] = love.math.random(50,300)
  sa["y"] = love.math.random(50,300)
  -- 去重逻辑
  -- for k,v in ipairs(allSa) do
  --   if v["text"] == sa["text"] then
  --     sa["text"] = string.sub(alphabets,pos,pos)
  --     break
  --   end
  -- end
  table.insert(allSa,sa)
  waitSeconds = initWaitSeconds
end

function drawKey(text,x,y)
  love.graphics.print(text,font,x,y)
end